package com.huayanginfo.saas.datasource;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;

import com.huayanginfo.saas.directory.JNDIService;
import com.huayanginfo.saas.member.ThreadLocalJNDIURL;

/**
 * 使用前提是通过Struts2 action的拦截器设置了threadlocal jndiulr，否则，需先设置threadlocal jndiurl
 * Spring的动态数据库连接类
 * @author rabbit
 *
 */
public class DynamicConnectionProvider implements DataSource{
	
	@Override
	public Connection getConnection() throws SQLException {
		return getJNDIDataSource().getConnection();
	}
	
	private BasicDataSource getJNDIDataSource(){
		String jndiURL = ThreadLocalJNDIURL.getJNDIURL();
		BasicDataSource basicDataSource = null;
		try {
			basicDataSource = JNDIService.getDataSource(jndiURL);
		} catch (NamingException e) {
			e.printStackTrace();
		}
		return basicDataSource;
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		return getJNDIDataSource().getLogWriter();
	}

	@Override
	public void setLogWriter(PrintWriter logWriter) throws SQLException {
		getJNDIDataSource().setLogWriter(logWriter);
	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		throw new UnsupportedOperationException("Not supported by DynamicConnectionProvider");
		
	}

	@Override
	public int getLoginTimeout() throws SQLException {
		throw new UnsupportedOperationException("Not supported by DynamicConnectionProvider");
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		throw new SQLException("DynamicConnectionProvider is not a wrapper.");
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return false;
	}

	@Override
	public Connection getConnection(String username, String password)
			throws SQLException {
		throw new UnsupportedOperationException("Not supported by DynamicConnectionProvider");
	}

}
